package com.example.android.dnd;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.DragEvent;
import android.view.View;
import android.widget.TextView;

public class RobotView extends View {
	private TextView resultText;

	private final Bitmap robot1 = BitmapFactory.decodeResource(getContext()
			.getResources(), R.drawable.robot1);
	private final Bitmap robot2 = BitmapFactory.decodeResource(getContext()
			.getResources(), R.drawable.robot2);
	private final Bitmap robot3 = BitmapFactory.decodeResource(getContext()
			.getResources(), R.drawable.robot3);

	private boolean isDragging;
	private boolean isHovering;

	public RobotView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void setResultTextView(TextView resultText) {
		this.resultText = resultText;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		Bitmap bitmap;
		if (isDragging) {
			if (isHovering) {
				bitmap = robot3;
			} else {
				bitmap = robot2;
			}
		} else {
			bitmap = robot1;
		}

		float x = (getWidth() - bitmap.getWidth()) / 2;
		canvas.drawBitmap(bitmap, x, getHeight() - bitmap.getHeight(), null);
	}

	@Override
	protected void onMeasure(int widthSpec, int heightSpec) {
		setMeasuredDimension(robot3.getWidth(), robot3.getHeight());
	}

	@Override
	public boolean onDragEvent(DragEvent event) {
		switch (event.getAction()) {
		case DragEvent.ACTION_DRAG_STARTED:
			isDragging = true;
			invalidate();
			break;

		case DragEvent.ACTION_DRAG_ENDED:
			isDragging = false;
			isHovering = false;
			invalidate();
			break;

		case DragEvent.ACTION_DRAG_LOCATION:
			break;

		case DragEvent.ACTION_DROP:
			resultText.setText("Dropped on Robot");
			break;

		case DragEvent.ACTION_DRAG_ENTERED:
			isHovering = true;
			invalidate();
			break;

		case DragEvent.ACTION_DRAG_EXITED:
			isHovering = false;
			invalidate();
			break;
		}

		return true;
	}
}